﻿using Demo.Api.Config;
using Demo.Api.Controllers.BasicData;
using Demo.Interface;
using Demo.Interface.BasicData;
using Demo.Model.Dto.User;
using Demo.Model.Entitys;
using Demo.Model.Other;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.Dto.User;

namespace Demo.Api.Controllers.Commin
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[AutoValidateAntiforgeryToken]
    [Authorize]
    public class LoginController : ControllerBase
    {
        public readonly IUserService _userService;
        public readonly ICustomJWTService _jWTService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public LoginController(ICustomJWTService jWTService, IUserService userService, IHttpContextAccessor httpContextAccessor)
        {
            _jWTService = jWTService;
            _userService = userService;
            _httpContextAccessor = httpContextAccessor;
        }
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]//版本控制
        [AllowAnonymous]//自定义鉴权
        [NoLogin]
        public async Task<ApiResult> GetToken(UserLogin users)
        {
            var res = Task.Run(() =>
            {
                if (string.IsNullOrEmpty(users.Name) || string.IsNullOrEmpty(users.Password))
                {
                    return ResultHelper.Error("参数不能为空");
                }
                UserRes user = _userService.GetUser(users.Name, users.Password);
                if (string.IsNullOrEmpty(user.Name))
                {
                    return ResultHelper.Error("账号不存在，用户名或密码错误!");
                }
                var token = _jWTService.GetToken(user);
                var data = _jWTService.GetUsers(users);
                // 设置Swagger自动登录
                _httpContextAccessor.HttpContext.SigninToSwagger(token);
                //HttpContextExtensions
                //_httpContextAccessor.HttpContext.SigninToSwagger
                return ResultHelper.Success(new {token,data}, "请求成功");
            });
            return await res;
        }
        [HttpGet]
        [ApiExplorerSettings(GroupName = "v1")]//版本控制
        public async Task<ApiResult> GetUserAll()
        {

            var res = Task.Run(() =>
            {
                var list = _userService.GetUserAll();
                return ResultHelper.Success(list, "请求成功");
            });
            return await res;
            //return Json(new { code = 0, data = list, msg = 1 });
        }
    }
}
